package com.cl.auth.stateless;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.cl.auth.AuthService;
import com.cl.entity.UUser;

import java.util.LinkedHashSet;
import java.util.Set;

public class StatelessRealm extends AuthorizingRealm {
	
    private static final Logger LOGGER = LoggerFactory.getLogger(StatelessRealm.class);
    
    
    @Autowired
    private AuthService authService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof StatelessToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        LOGGER.debug("StatelessRealm doGetAuthenticationInfo");
        StatelessUser user = (StatelessUser) getAvailablePrincipal(principalCollection);
        Set<String> roleNames = new LinkedHashSet<String>();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
        info.setStringPermissions(user.getPermissions());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        LOGGER.debug("StatelessRealm doGetAuthenticationInfo");
        StatelessToken statelessToken = (StatelessToken) authenticationToken;
        String accessToken = statelessToken.getAccessToken();
        boolean available = authService.getTokenAvailable(accessToken);
        StatelessUser user = authService.getUser(accessToken);
        return new SimpleAuthenticationInfo(user, available, getName());
    }

}